package server

import (
	"fmt"
	"gin-fileserver/middleware/crossfield"
	"gin-fileserver/middleware/safety"
	"gin-fileserver/pkg/logger"
	"gin-fileserver/pkg/setting"

	log "github.com/sirupsen/logrus"

	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

type ServerConfig struct {
	UploaderCfg Uploader
	DownloadCfg Downloader
}

func Setup(cfg ServerConfig) {
	// 检查文件路径
	if err := CheckImageServerPath(); err != nil {
		log.Panicln(err)
	}

	gin.SetMode(setting.Cfg.RunMode)
	r := gin.New()
	r.Use(logger.GinLogger())
	r.Use(gin.Recovery())
	// 解决跨域问题
	r.Use(crossfield.CrossField())
	// 解决安全问题
	r.Use(safety.Safety())

	setupUploader(cfg.UploaderCfg, r)
	setupDownloader(cfg.DownloadCfg, r)

	s := &http.Server{
		Addr:           fmt.Sprintf(":%d", setting.Cfg.HTTPSetting.Port),
		Handler:        r,
		ReadTimeout:    time.Duration(setting.Cfg.HTTPSetting.ReadTimeout) * time.Second,
		WriteTimeout:   time.Duration(setting.Cfg.HTTPSetting.WriteTimeout) * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	// s.ListenAndServeTLS("cert/cert.pem", "cert/cert.key")
	s.ListenAndServe()

	defer s.Close()
}
